package com.it.zuoning.sbh.file.utils;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.http.HttpServletResponse;
import java.io.*;

/**
 * @ClassName FileUtils
 * @Description: 文件处理器
 * @Author 小白
 * @Date 2019/12/15
 * @Version V1.0
 **/
public abstract class FileUtils {

    private static Logger LOGGER = LoggerFactory.getLogger(FileUtils.class);

    public static void downloadFile(File file, HttpServletResponse response){
        try {

            // 以流的形式下载文件。
            InputStream fis = new BufferedInputStream(new FileInputStream(file));
            byte[] buffer = new byte[fis.available()];
            fis.read(buffer);
            fis.close();
            // 清空response
            response.reset();
            // 设置response的Header
            response.addHeader("Content-Disposition", "attachment;filename=" + new String(file.getName()));
            response.addHeader("Content-Length", "" + file.length());
            OutputStream toClient = new BufferedOutputStream(response.getOutputStream());
            response.setContentType("application/octet-stream");
            toClient.write(buffer);
            toClient.flush();
            toClient.close();
        } catch (IOException ex) {
            LOGGER.error("文件下载失败 e{}", ex);
        }
    }
}
